package com.duqc.util;

/**
 * @ClassName SnowflakeIdUtil
 * @Description SnowflakeIdUtil
 * @Author duqc
 * @Date 2022/11/09
 **/
public class SnowflakeIdUtil {

    private static final long WORKER_ID_BITS = 10;

    /**
     * 毫秒内序列，12位，2^12 = 4096个数字
     */
    private static long sequence = 0L;

    /**
     * 上一次生成的ID的时间戳，同一个worker中
     */
    private static long lastTimestamp = -1L;

    /**
     * 默认workerId
     */
    private static final long WORKER_ID = 1L;

    public SnowflakeIdUtil() {
        long maxWorkerId = ~(-1L << WORKER_ID_BITS);
        if (WORKER_ID > maxWorkerId || WORKER_ID < 0) {
            throw new IllegalArgumentException(String.format("WorkerId必须大于或等于0且小于或等于%d", maxWorkerId));
        }
    }

    public static synchronized long nextId() {
        long ts = System.currentTimeMillis();
        if (ts < lastTimestamp) {
            throw new RuntimeException(String.format("系统时钟回退了%d毫秒", (lastTimestamp - ts)));
        }
        //同一时间内，则计算序列号
        long sequenceBits = 12;
        if (ts == lastTimestamp) {
            //序列号溢出
            long maxSequence = ~(-1L << sequenceBits);
            if (++sequence > maxSequence) {
                ts = tilNextMillis(lastTimestamp);
                sequence = 0L;
            }
        } else {
            // 时间戳改变，重置序列号
            sequence = 0L;
        }
        lastTimestamp = ts;
        //开始时间
        long beginTs = 1420042600000L;
        //时间戳左移22位
        long timestampLeftOffset = WORKER_ID_BITS + sequenceBits;
        // 0 - 00000000 00000000 00000000 00000000 00000000 0 - 00000000 00 - 00000000 0000
        // 左移后，低位补0，进行按位或运算相当于二进制拼接
        return (ts - beginTs) << timestampLeftOffset | WORKER_ID << sequenceBits | sequence;
    }

    /**
     * 阻塞到下一秒
     *
     * @param lastTimestamp 上一次生成的ID的时间戳
     * @return long
     */
    private static long tilNextMillis(long lastTimestamp) {
        long ts = System.currentTimeMillis();
        while (ts <= lastTimestamp) {
            ts = System.currentTimeMillis();
        }
        return ts;
    }

}
